package com.tianluo.tianluobookstore.filter;

import com.tianluo.tianluobookstore.service.RedisService;
import com.tianluo.tianluobookstore.util.JwtTokenUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {

        System.out.println("666" + request.getRequestURL() + "888" + request.getRequestURI());
        if (request.getRequestURI().endsWith(".html")) {
            return true;
        }

        //请求头获取token
        String token = request.getHeader("Authorization");

        if (token == null || !token.startsWith("Bearer ")) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("Invalid token");
            return false;
        }

        //验证token 是否过期
        String jwt = token.replace("Bearer ", "");
        if (jwtTokenUtil.isTokenExpired(jwt)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("Token expired");
            return false;
        }


        Claims claims = jwtTokenUtil.extractClaims(jwt);
        //我们登录时，把手机号塞进去，因为可以解析出来，查询用户信息
        String phoneNumber = claims.getSubject();

        String tidInRedis = redisService.get(phoneNumber);
        if(StringUtils.isBlank(tidInRedis)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("Token expired");
            return false;
        }

        System.out.println("拦截器截取 phoneNumber:" + phoneNumber);
        //手机号码，放到request attributes
        request.setAttribute("phoneNumber", phoneNumber);

        return true;
    }
}